<template>
  <el-container>
    <el-main v-loading="loading">
      <el-table :data="userList">
        <el-table-column prop="name" label="角色姓名" />
        <el-table-column prop="stateName" label="角色状态" />
        <el-table-column label="操作" width='220'>
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="stopClick(scope.row)" type="text" size="small">{{scope.row.state === 0 ? '停用': '启用'}}</el-button>
            <el-button type="text" size="small" @click="delMsg(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%">
        <span>{{dialogContent}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sure">确 定</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>
<script>
const tips = ['确认启用该角色信息?','确认停用该角色信息?','确认删除该角色信息?'];
let state = ['edit','stop','del']; //操作状态
export default {
  name: "systemRoletable",
  props:['data', 'loading'],
  data() {
    return {
      userList: [],
      dialogContent: '',
      dialogVisible: false,
      type: '', //操作状态
      id:'',
    };
  },
  methods: {
    handleClick(params) {
      this.id = params.id;
      this.type = state[0];
      this.$router.push(`roleAdd?type=edit&id=${this.id}`);
    },
    stopClick(params){
      this.id = params.id;      
      this.type = state[1];
      this.dialogVisible = true;
      if(params.state === 0) return this.dialogContent = tips[1];
      this.dialogContent = tips[0];
    },
    delMsg(params) {
      this.id = params.id;
      this.type = state[2];      
      this.dialogContent = tips[2];
      this.dialogVisible = true;
    },
    delApi(){
      this.api.delete(`/role/${this.id}`).then(()=>{
        this.userList = this.userList.filter(item=>{
          return item.id !== this.id
        })
      }).catch((err) => {
        this.$message(err.message)
      })
      this.dialogVisible = false;
    },
    stopApi(){
      let user = this.lodash.filter(this.userList, item =>{
        return item.id === this.id;
      })
      let { id, state } = user[0];
      if (state === 0){
        state = -1;
      }else{
        state = 0;
      }
      let params = {state, id};
      this.api.put(`/role`, params).then(()=>{
        this.$emit("search");
      }).catch((err) => {
        console.log(err)
        this.$message(err.data.message)
      })
      this.dialogVisible = false;
    },
    sure(){
      if(this.type === 'del') return this.delApi();
      if(this.type === 'stop') return this.stopApi();
    }
  },
  watch:{
    data(newValue){
      this.userList = newValue;
    }
  }
};
</script>
<style lang="less" scoped>
</style>